package com.heima.search.service.impl;

import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.UserSearchService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-20 15:48
 */
@Service
@Slf4j
public class UserSearchServiceImpl implements UserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    @Async
    public void save(String searchWords,Integer id) {

        //1.查询搜索记录
        List<ApUserSearch> list = mongoTemplate.
                find(Query.query(Criteria.where("keyword").is(searchWords)
                        .and("userId").is(id)), ApUserSearch.class);

        //已经存在，更新时间
        if(!CollectionUtils.isEmpty(list)){
            ApUserSearch apUserSearch = list.get(0);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //把当前用户所有数据都取出来，然后再判断是否超过10条
        List<ApUserSearch> list2 = mongoTemplate.
                find(Query.query(Criteria.where("userId").is(id)), ApUserSearch.class);

        if(list2.size() >= 10){
            //替换最后一条
            List<ApUserSearch> sortList = list2.stream().
                    sorted(Comparator.comparing(ApUserSearch::getCreatedTime).reversed()).collect(Collectors.toList());
            ApUserSearch apUserSearch = sortList.get(sortList.size() - 1);
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);

        }else{
            //小于10条，新增数据
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setUserId(id);
            apUserSearch.setCreatedTime(new Date());

            mongoTemplate.save(apUserSearch);
        }

    }

    @Override
    public List<ApUserSearch> load() {

        return mongoTemplate.find(Query.query(Criteria.where("userId").is(AppThreadLocalUtil.getUser().getId())
        ).with(Sort.by(Sort.Direction.DESC, "createTime")),ApUserSearch.class);
    }

    @Override
    public void delete(String id) {
        //必须添加userId，保证操作人是我本人
        mongoTemplate.remove(Query.query(Criteria.where("id").is(id)
                .and("userId").is(AppThreadLocalUtil.getUser().getId())),ApUserSearch.class);
    }
}
